﻿Imports Send2Twitter
Imports iTunesLib
Imports System.Collections.Specialized
Imports System.ComponentModel.Composition

<ExportCompent(GetType(IInfoProvider), "iTunes", "731fcc74-7298-4316-b685-38b199593ebb", "1.0.0.1")>
Public Class iTunesInfoGen
    Inherits InfoProviderBase

    Protected iTApp As iTunesApp

    Public Overrides Function GetAvailability() As Boolean
        If Not IsiTunesStarted() Then Return False
        If iTApp Is Nothing Then Return False
        Return iTApp.PlayerState = ITPlayerState.ITPlayerStatePlaying
    End Function

    Public Overrides Function GetInfo() As Dictionary(Of String, String)
        Dim r As New Dictionary(Of String, String)()
        If iTApp Is Nothing Then
            If IsiTunesStarted() Then
                StartUp()
            Else
                Return r
            End If
        End If
        Dim t = iTApp.CurrentTrack
        On Error Resume Next
        r.Add("album", t.Album)
        r.Add("artist", t.Artist)
        r.Add("bitrate", t.BitRate.ToString)
        r.Add("bpm", t.BPM)
        r.Add("comment", t.Comment)
        r.Add("composer", t.Composer)
        r.Add("disccount", t.DiscCount.ToString)
        r.Add("disc", t.DiscNumber)
        r.Add("genre", t.Genre)
        r.Add("grouping", t.Grouping)
        r.Add("index", t.Index.ToString)
        r.Add("filetype", t.KindAsString)
        r.Add("title", t.Name)
        r.Add("playedcount", t.PlayedCount.ToString)
        r.Add("compilation", t.Compilation)
        r.Add("rating", t.Rating.ToString)
        r.Add("samplerate", t.SampleRate)
        r.Add("size", t.Size.ToString)
        r.Add("trackcount", t.TrackCount)
        r.Add("track", t.TrackNumber)
        r.Add("year", t.Year.ToString)
        r.Add("volumeadjustment", t.VolumeAdjustment.ToString)
        r.Add("compilation", t.Compilation.ToString)
        r.Add("tracktime", t.Time.ToString)
        r.Add("trackcount", t.TrackCount)
        On Error GoTo 0
        Return r
    End Function

    Public Overrides Sub ShutDown()
        If iTApp IsNot Nothing Then
            Runtime.InteropServices.Marshal.ReleaseComObject(iTApp)
        End If
        iTApp = Nothing
    End Sub

    Public Overrides Sub StartUp()
        If IsiTunesStarted() Then
            iTApp = New iTunesApp()
        Else
            iTApp = Nothing
        End If
    End Sub

    Private Function IsiTunesStarted() As Boolean
        If Process.GetProcessesByName("iTunes").Length > 0 Then
            Return True
        Else
            Return False
        End If
    End Function
End Class
